import os
import sys
import math
import numpy
import lxml.etree as ET
import png2obj.image
import png2obj.heightmap
import png2obj.minecraft
import png2obj.stardrive.hull

if len(sys.argv) < 2:
    print('Takes an image filename as an argument.')
else:
    filename = sys.argv[1]
    
    head, tail = os.path.split(filename)
    name, ext = os.path.splitext(tail)

    
    if ext == ".xml":
        tree = ET.parse(filename)
        shipData = tree.getroot()
        name = shipData.findtext("Name")
        slots = png2obj.stardrive.hull.shipData2Slots(shipData)
    else:
        imageData = png2obj.image.loadImage(filename)
        slots = png2obj.stardrive.hull.imageData2Slots(imageData, ("O", "I", "E"))
        
    # mesh generation
    numSlots = png2obj.stardrive.hull.countSlotRestrictionSets(slots)
    area = float(sum(numSlots[1:]))
    baseHeight = 1.0/16.0 * area**(1.0/2.0)
    heights = numpy.zeros_like(slots, float)
    heights[slots == 1] = math.ceil(3.0 * baseHeight)
    heights[slots == 2] = math.ceil(1.0 * baseHeight)
    heights[slots == 3] = math.ceil(2.0 * baseHeight)
    heights[slots == 4] = math.ceil(3.0 * baseHeight)
    mesh, placeholderTextureData = png2obj.minecraft.minecraftStyle(name, heights, placeholderScale = 4)
    mesh.exportWavefront(head)
    png2obj.image.saveImage(os.path.join(head, name + "_d.png"), placeholderTextureData)

    if ext == ".png":
        # xml generation
        print("Slot counts: " + str(numSlots)) # empty, I, O, IO, E, IE, OE, IOE
        numAsy = png2obj.stardrive.hull.countAsymmetricalSlotPairs(slots)
        print('%s: %d asymmetrical slot pair(s)' % (name, numAsy))
        shipData = png2obj.stardrive.hull.defaultHullXML(slots, name)
        tree = ET.ElementTree(shipData)
    
        tree.write(os.path.join(head, name + ".xml"), xml_declaration=True, pretty_print=True, encoding='utf-8')

